package pl.edu.agh.agents.gui.actions;

import java.util.ArrayList;
import java.util.List;

import pl.edu.agh.agents.agent.Agent;
import pl.edu.agh.agents.agent.SystemManager;
import pl.edu.agh.agents.gui.GUI;
import pl.edu.agh.agents.gui.GraphUtils;

// repeatedly calls systemManager.iteration
public class IterationThread extends Thread {
	private SystemManager systemManager = SystemManager.getInstance();
	private GraphUtils graphUtils = GraphUtils.getInstance();
	// to stop thread safely
	private volatile boolean stop = false;
	private GUI gui;

	public IterationThread(GUI gui) {
		this.gui = gui;
	}

	public void requestStop() {
		stop = true;
	}

	@Override
	public synchronized void run() {
		while (true) {
			stop = false;

			try {
				Thread.sleep(gui.getDelay());
			}
			catch (InterruptedException e) { }

			// safe method for stopping thread
			if (stop || systemManager.isFinished() || systemManager.isBlocked()) {
				stop = false;
				// enable and disable buttons
				gui.stopIterationThread();
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			List<pl.edu.agh.agents.state.State> statesToColor = new ArrayList<pl.edu.agh.agents.state.State>();
			int currentAgentID = (systemManager.getCurrentAgentID() + 1) % gui.getAgents().size();
			Agent currentAgent = gui.getAgents().get(currentAgentID);
			
			statesToColor.add(currentAgent.getCurrentState());

			systemManager.makeIterationForOne();
			
			statesToColor.add(currentAgent.getCurrentState());
			
			// update colors of states
			graphUtils.colorStates(gui);
		}
	}
}